﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace Smtp_server
{
    class Daemon_smtp
    {
        private ILogger ilogger;
        private DBagent dbagent;
        private TcpListener server;
        private Int32 port;
        private IPAddress localAddr;

        public Daemon_smtp(ILogger ilogger, DBagent dbagent)
        {
            this.ilogger = ilogger;
            this.dbagent = dbagent;
            this.server = null;

            // Set the TcpListener on port 13000.
            port = Macros.port;
            localAddr = IPAddress.Parse(Macros.localip);
        }

      
        public void Start()
        {
            try
            {
                // TcpListener server = new TcpListener(port);
                server = new TcpListener(IPAddress.Any, port);
                
                // Start listening for client requests.
                server.Start();

               
                // Enter the listening loop.
                while (true)
                {
                    ilogger.Write("Waiting for a connection... \r\n");
                    
                    // Perform a blocking call to accept requests.
                    // You could also user server.AcceptSocket() here.
                    TcpClient client = server.AcceptTcpClient();

                    Daemon_connection dconn = new Daemon_connection(client,ilogger,dbagent);
                    Thread clientThread = new Thread(new ThreadStart(dconn.Run));
                    clientThread.Start();
                    

                    
                }
            }
            catch (SocketException e)
            {
                ilogger.Write("SocketException: {0}"+ e+"\r\n");
            }
            finally
            {
                // Stop listening for new clients.
                server.Stop();
            }


            ilogger.Write("End...\r\n");
        }

        public void Stop()
        {
            // Stop listening for new clients.
            server.Stop();
            ilogger.Write("Stopped...\r\n");
        }

        
    }
}

